package androidx.gdata.documents;

import android.util.Log;

import org.w3c.dom.Node;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;

import androidx.gdata.GDataServer;
import androidx.gdata.documents.xml.EntryDeserializer;
import androidx.gdata.documents.xml.EntrySerializer;

public class DocumentsServerImpl extends GDataServer implements DocumentsServer {

  private URL url;
  private static final EntrySerializer entrySerializer = new EntrySerializer();
  private static final EntryDeserializer entryDeserializer = 
    new EntryDeserializer();
  private static final String uploadURL = "http://docs.google.com/feeds/" +
  "default/private/full?v=3";

  protected DocumentsServerImpl(String baseUrl, String username, String auth) {
    super(baseUrl, username, auth);
    try {
      url = new URL(baseUrl);
    } catch (MalformedURLException e) {
      throw new RuntimeException("Bad URL!", e);
    }
  }

  public Entry uploadDocument(Entry entry) throws IOException {
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    entrySerializer.serialize(out, entry);
    out.flush();
    URL url = new URL(uploadURL);
    String atomPost = sw.toString();
    Log.i("Notes", "Posting " + atomPost);
    String rv = doAtomPost(url, atomPost);
    Log.i("Notes", "Post response from upload " + rv);
    Node entryNode = extractEntryNode(rv);
    return entryDeserializer.build(entryNode);
  }


}
